package com.weimob.xh.controller.workhf;

import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@RestController
public class FileDownloadController {

    @GetMapping("/download")
    public ResponseEntity<ByteArrayResource> downloadFile() throws IOException {
        // 创建一个空的 ZIP 输出流
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream);

        // 添加一个示例文件到 ZIP 文件中
        String fileName = "example.txt";
        String fileContent = "This is an example file.";
        ZipEntry zipEntry = new ZipEntry(fileName);
        zipOutputStream.putNextEntry(zipEntry);
        zipOutputStream.write(fileContent.getBytes());
        zipOutputStream.closeEntry();

        // 关闭 ZIP 输出流并获取字节数组
        zipOutputStream.close();
        byte[] bytes = byteArrayOutputStream.toByteArray();

        // 创建响应实体并设置内容类型和下载属性
        ByteArrayResource resource = new ByteArrayResource(bytes);
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=example.zip");
        headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);

        return ResponseEntity.ok().headers(headers).body(resource);
    }
}
